package basic.study.wantOffer.chapter2;

/**
 * @author Kevin
 * @date 2020/4/27 13:44
 * 二维数组中的查找，二维数组从左到右，从上到下递增，找value
 * 做法：选取数组右上角的数字，该数字大于value，则删除所在列；该数字小于value，则删除所在行
 */
public class Problem4 {
    public static void main(String[] args) {
        int[][] arr = {{1, 2, 8, 9},
                {2, 4, 9, 12},
                {4, 7, 10, 13},
                {6, 8, 11, 15}};

        System.out.println(search(arr, 7));
    }

    private static boolean search(int[][] arr, int value) {
        int cols = arr[0].length;
        int rows = arr.length;
        int row = 0;
        int col = cols - 1;

        while (row < rows && col >= 0) {
            if (arr[row][col] == value) {
                return true;
            }
            if (arr[row][col] < value) {
                row++;
            } else {
                col--;
            }
        }
        return false;
    }
}
